package com.android.lovely.framework.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.view.marginBottom
import androidx.core.view.marginTop

class EdgeLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private var originalTouchY = 0f
    private var originalViewY = 0f
    private var lastTouchDownTime = 0L

    private val isClick: Boolean
        get() = System.currentTimeMillis() - lastTouchDownTime < CLICK_THRESHOLD

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> handleDownEvent(event)
            MotionEvent.ACTION_MOVE -> handleMoveEvent(event)
            MotionEvent.ACTION_UP -> handleUpEvent()
            else -> super.onTouchEvent(event)
        }.also { handleParentTouchIntercept(event) }
    }

    private fun handleDownEvent(event: MotionEvent): Boolean {
        originalTouchY = event.rawY
        originalViewY = y
        lastTouchDownTime = System.currentTimeMillis()
        return true
    }

    private fun handleMoveEvent(event: MotionEvent): Boolean {
        val targetY = originalViewY + (event.rawY - originalTouchY)
        y = calculateValidY(targetY)
        return true
    }

    private fun handleUpEvent(): Boolean {
        if (isClick) performClick()
        return true
    }

    private fun handleParentTouchIntercept(event: MotionEvent) {
        parent.requestDisallowInterceptTouchEvent(event.actionMasked == MotionEvent.ACTION_MOVE)
    }

    private fun calculateValidY(targetY: Float): Float {
        val maxY = (parent as? ViewGroup)?.let { it.height - height - marginBottom } ?: 0f
        return targetY.coerceIn(marginTop.toFloat(), maxY.toFloat())
    }

    companion object {
        private const val CLICK_THRESHOLD = 150L
    }
}